package com.ys.controller.api.storage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ys.config.MenuId;
import com.ys.entity.base.TbCountry;
import com.ys.entity.shiro.LoginUser;
import com.ys.entity.storage.TccLogisticsMethod;
import com.ys.entity.storage.TccWarehouse;
import com.ys.entity.sys.TsOrganizationInfo;
import com.ys.entity.sys.YsCol;
import com.ys.enume.storage.TccLogisticsMethodItemEnum;
import com.ys.enume.sys.YsRoleMenuEnum;
import com.ys.mapper.storage.StorageMapper;
import com.ys.mapper.sys.SysMapper;
import com.ys.service.storage.TccLogisticsMethodService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: fxz
 * @CreateTime: 2024-12-05
 * @Description: 物流方式
 * @Version: 1.5
 */
@Controller
@RequestMapping("/api/inter/tccLogisticsMethod")
public class ApiInterTccLogisticsMethodController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTccLogisticsMethodController.class);
    
    @Autowired
    private TccLogisticsMethodService tccLogisticsMethodService;

    @Autowired
    private CommonApiService<TccLogisticsMethod> commonApiService;

    //菜单id
    private Long menuId = MenuId.TCC_LogisticsMethod;

    @Autowired
    private StorageMapper storageMapper;

    @Autowired
    private SysMapper sysMapper;


    /**
     * 查询
     */
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TccLogisticsMethod cond, String conditions
    ){
        try {
            cond = setSeachSql(cond);
            LayuiTableVoJA setList = commonApiService.searchLay(cond);
            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }



    /**
     * 查询
     */
    @RequestMapping("/searchByModal")
    @ResponseBody
    public LayuiTableVoJA searchByModal(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TccLogisticsMethod cond, String conditions
    ){
        try {
            cond = setSeachSql(cond);

            //调取未被调取的
            cond.where("( SELECT COUNT ( 1 ) AS num FROM TCC_LogisticsChannelMaint B WHERE B.LogsticsWay = A.LogsticsWay ) = 0 ");
            cond = dataAuth(menuId, cond);
            LayuiTableVoJA setList = commonApiService.searchLay(cond);
            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }




    /**
    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TccLogisticsMethod setSeachSql(TccLogisticsMethod cond){

        cond.addLeftJoin("TCC_Warehouse B ON B.Cck=A.Cck")
                .addLeftJoin("TB_Country C ON C.Code=A.DestinationCountryCode")
                .addField("B.Vck vck,C.Name destinationCountryName")
                //排序
                .setOrderby("A.logsticsWay ASC");

        cond = dataAuth(menuId, cond);
        return  cond;
    }


    //特殊的权限控制
    public TccLogisticsMethod dataAuth(Long menuId,TccLogisticsMethod cond){
        Long roleId = ShiroUtils.getRoleId();
        if (roleId.longValue() == 1L) {
            return cond;
        }
        Integer type = sysMapper.getTypeOfRoleMenu(roleId, menuId);
        if (type == YsRoleMenuEnum.Type.USER.value) {
            String userId = ShiroUtils.getUserId();
            Integer authType = type;
            List<YsCol> listYsCol = new YsCol().setMenuId(menuId).setAuthType(authType).queryList();
            for(YsCol ysCol : listYsCol) {
                String fieldCode = ysCol.getFrontConditionCode() != null && ysCol.getFrontConditionCode().length() > 0 ? ysCol.getFrontConditionCode() : ("A." + ysCol.getCode());
//				condSql = condSql + (fieldCode + " = '" + userId + "' and ");
                cond.where(fieldCode + " = '" + userId + "'");
            }
        } else if (type == YsRoleMenuEnum.Type.DEPT.value) {
            Long orgId = ShiroUtils.getOrgId();
            TsOrganizationInfo tsOrganizationInfo = new TsOrganizationInfo().setId(orgId).queryFirst();
            Integer authType = type;
            List<YsCol> listYsCol = new YsCol().setMenuId(menuId).setAuthType(authType).queryList();
            for(YsCol ysCol : listYsCol) {
                String fieldCode = ysCol.getFrontConditionCode() != null && ysCol.getFrontConditionCode().length() > 0 ? ysCol.getFrontConditionCode() : ("A." + ysCol.getCode());
                cond.addLeftJoin("TS_OrganizationInfo X_97 ON X_97.OrgId = " + fieldCode)
                        .where("X_97.NodeLft >= " + tsOrganizationInfo.getNodeLft() + " AND X_97.NodeRgt <= " + tsOrganizationInfo.getNodeRgt());
            }
        } else if (type == YsRoleMenuEnum.Type.OPERATOR.value) {
            LoginUser loginUser = ShiroUtils.getLoginUser();
            Integer authType = type;
            List<YsCol> listYsCol = new YsCol().setMenuId(menuId).setAuthType(authType).queryList();
            for(YsCol ysCol : listYsCol) {
                String fieldCode = ysCol.getFrontConditionCode() != null && ysCol.getFrontConditionCode().length() > 0 ? ysCol.getFrontConditionCode() : ("A." + ysCol.getCode());
               String mainTable = "SELECT DISTINCT AA.* FROM TCC_LogisticsMethod AA " +
                       " LEFT JOIN TCC_LogisticsCompanyApply YS_99 ON  YS_99.MethodId = AA.Id " +
                       " LEFT JOIN THR_OperateCompanyApply X_98 ON X_98.VGsbm =  " + fieldCode +
                       " LEFT JOIN TS_OperateOrg X_99 ON X_99.Id = X_98.OperateOrgId " +
                       " WHERE YS_99.Id IS NULL OR ( X_99.NodeLft >= " + loginUser.getOperateOrgNodeLft() + "AND X_99.NodeRgt <= " + loginUser.getOperateOrgNodeRgt()+")";

                cond.setMainTable("("+mainTable+")");
//
//                cond.addLeftJoin("LEFT JOIN TCC_LogisticsCompanyApply YS_99 ON  YS_99.MethodId = A.Id ");
//                cond.addLeftJoin("THR_OperateCompanyApply X_98 ON X_98.VGsbm = " + fieldCode)
//                        .addLeftJoin("TS_OperateOrg X_99 ON X_99.Id = X_98.OperateOrgId")
//                        .where("YS_99.Id IS NULL OR ( X_99.NodeLft >= " + loginUser.getOperateOrgNodeLft() + "AND X_99.NodeRgt <= " + loginUser.getOperateOrgNodeRgt()+")");

            }
        }
        return cond;
    }



    @RequestMapping("/searchFbaPlan")
    @ResponseBody
    public LayuiTableVoJA searchFbaPlan(@ModelAttribute TccLogisticsMethod cond,Long shopId,String vgsbm,String warehouseCode){
        cond    .addField("case when divisionalRule = 0 then '0.1kg进1kg' when divisionalRule = 1 then '0.5kg进1kg' else '不约分' end as divisionalRuleName")//约分规则
                .addField("case when coefficientWeight = 0 then '5000'else '6000' end as coefficientWeightName")//抛货系数
                .addLeftJoin("TCC_Warehouse F ON F.Cck = A.Cck")
                .addLeftJoin("TP_AmazonShop B ON B.id = " + shopId)
                .addLeftJoin("TB_Site C ON C.id = B.SiteId")
                .addLeftJoin("TB_Country D ON D.id = C.CountryId")
                .setStatus(1)
        .where("D.Code = A.DestinationCountryCode")
        //判断是否允许该公司调取物流服务
        .where("((SELECT count(1) FROM TCC_LogisticsCompanyApply WHERE  MethodId = A.id) = 0) OR ((SELECT count(1) FROM TCC_LogisticsCompanyApply WHERE  MethodId = A.id AND vgsbm ='"+ vgsbm +"') != 0) ")
        ;
        //仓库目的地列表为空查全部，不为空排除禁止的目的地不让调取
        if (warehouseCode != null){
            cond.where("((SELECT count(1) FROM TCC_AdditionalBillingTwo WHERE   MethodId = A.id) = 0) OR ((SELECT count(1) FROM TCC_AdditionalBillingTwo WHERE  MethodId = A.id AND warehouseCode !='"+ warehouseCode +"') != 0) ");
        }
        cond.setOrderby("A.logsticsWay ASC");
        LayuiTableVoJA vo = commonApiService.searchLay(cond);
        return vo;
    }

    /**
     * 逸思精品保存调货信息
     */
    @PostMapping("/editDetailBatch")
    @ResponseBody
    public R editDetailBatch(HttpServletRequest request,
                             Long logisticsMethodId, String detailArr){
        return tccLogisticsMethodService.editDetailBatch(logisticsMethodId, detailArr);
    }

    /*
     * 新增
     */
    @RequestMapping("/toAdd")
    @ResponseBody
    public R add(HttpServletRequest request,@RequestParam Map<String, Object> params) {
        try {

            //修改
            return tccLogisticsMethodService.add( params, menuId);
        } catch (Exception e) {
            logger.error("物流方式维护新增出错：", e.getMessage(), e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    /**
     * 修改
     */
    @RequestMapping("/toEdit")
    @ResponseBody
    public R edit(HttpServletRequest request,@RequestParam Map<String, Object> params) {
        try {
            return tccLogisticsMethodService.save(params, menuId);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }
    /**
     * 删除列表信息 - 运营公司表VPS信息
     */
    @RequestMapping("/del")
    @ResponseBody
    public R del(@RequestParam("list") List<String> idList){
        try {
            for(int i=0;i<idList.size();i++) {
                tccLogisticsMethodService.del(Long.parseLong(idList.get(i)));//删除
            }
            return R.ok();
        }catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }
    /**
     * 删除列表信息 - 材质附加计费标准
     */
    @RequestMapping("/del2")
    @ResponseBody
    public R del2(@RequestParam("list") List<String> idList){
        try {
            for(int i=0;i<idList.size();i++) {
                tccLogisticsMethodService.del(Long.parseLong(idList.get(i)));//删除
            }
            return R.ok();
        }catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }
    /**
     * 删除列表信息 - 抛重附加计费标准
     */
    @RequestMapping("/del3")
    @ResponseBody
    public R del3(@RequestParam("list") List<String> idList){
        try {
            for(int i=0;i<idList.size();i++) {
                tccLogisticsMethodService.del(Long.parseLong(idList.get(i)));//删除
            }
            return R.ok();
        }catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TccLogisticsMethod cond, String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond)
                    .addField("CASE WHEN A.TransportationId=0 THEN '快递' WHEN A.TransportationId=1 THEN '空运'" +
                            "WHEN A.TransportationId=2 THEN '卡航' WHEN A.TransportationId=3 THEN '铁路' " +
                            "WHEN A.TransportationId=4 THEN '海运' END  transportationName")
                    .addField("CASE WHEN A.NameLogsticsClearance=1 THEN '包税' WHEN A.NameLogsticsClearance=0 THEN '自税'" +
                            " END logsticsClearanceName");

            TccLogisticsMethod tccLogisticsMethod = JSON.parseObject(JSON.toJSONString(cond), TccLogisticsMethod.class);
            TccWarehouse tccWarehouse = JSON.parseObject(JSON.toJSONString(cond), TccWarehouse.class);
            TbCountry tbCountry = new TbCountry().setCode(cond.getDestinationCountryCode());

            String transportationName = ConditionUtil.getConditionValue(conditions, "transportationId");//运输类型

            String nameLogsticsClearance = ConditionUtil.getConditionValue(conditions, "nameLogsticsClearance");//清关方式

            String logsticsWay = ConditionUtil.getConditionValue(conditions, "logsticsWay");//物流服务名称
            if (logsticsWay != null){
                cond.where("[逸博" + tccWarehouse.getVck()+"]" +tbCountry.getName()+transportationName+"("+nameLogsticsClearance+")"+
                        tccLogisticsMethod.getEstimatedDayFrom()+"~"+ tccLogisticsMethod.getEstimatedDayTo()+"天"  );
            }

            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setFrontExport(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TccLogisticsMethod> util = new ExportExcelUtils<>(new TccLogisticsMethod());
            String toFilePath = util.exportExcel(listData, listField, "物流服务维护单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

}
